<?php
/**
 * Created by PhpStorm.
 * User: sogubaby
 * Date: 2019-03-13
 * Time: 17:52
 */

namespace App\Library\String;

class Aes {
    // 加密方式
    private $_cipher;
    // 密钥
    private $_key;
    // 非null的初始化向量
    private $_iv;
    // 选项 OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING
    private $_options;


    /**
     * Aes constructor.
     * @param string $cipher
     * @param $key
     * @param $iv
     * @param int $options
     */
    public function __construct($cipher = 'aes-128-cbc', $key = '', $iv = '', $options = OPENSSL_ZERO_PADDING) {
        $this->_cipher = $cipher;
        $this->_key    = config('union_login.union_sheng_bai_key');
        $this->_iv     = mb_substr($this->_key ,0,16,'utf8');
        $this->_options   = $options;
    }

    /**
     * aes加密
     * @param $data
     * @return string
     * @author luwei
     * @date 2019-03-14 00:32
     */
    public function encrypt(array $data) {
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $data = $data . str_repeat("\x00", 16 - (strlen($data) % 16));
        $ciphertext = openssl_encrypt($data, $this->_cipher, $this->_key, $this->_options, $this->_iv);
        return $ciphertext;
    }

    /**
     * aes解密
     * @param $cipherText
     * @return string
     * @author luwei
     * @date 2019-03-14 00:32
     */
    public function decrypt(string $cipherText) {
        $original_plaintext = openssl_decrypt($cipherText, $this->_cipher, $this->_key, $this->_options, $this->_iv);
        $original_plaintext = rtrim($original_plaintext);
        return $original_plaintext;
    }

}
